package com.niwodai.fintrade.report.model.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.niwodai.framework.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

@Slf4j
@Component
public class OssUtil {

    @Value("${oss.endpoint:oss-cn-shanghai.aliyuncs.com}")
    private String endpoint;
    @Value("${oss.access-key-id:LTAI5tR3bGpLaahWrY9fqkrJ}")
    private String accessKeyId;
    @Value("${oss.access-key-secret:DDqsSN6G39tpVct9n0CeBhwtYYQYaL}")
    private String accessKeySecret;
    @Value("${oss.bucket-name:zd-report-bucket-test}")
    private String bucketName;
    @Value("${oss.url.expiration-min:21600}")
    private Integer expirationMin;
    @Value("${oss.downloadEndpoint:oss-cn-shanghai.aliyuncs.com}")
    private String downloadEndpoint;

    private static final long partSize = 2 * 1024 * 1024L;

    private static final int taskNum = 1;

    public Boolean uploadFileWithResumable(String objectName, String filePath) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try{
            // 创建上传文件的请求
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, objectName);
            uploadFileRequest.setUploadFile(filePath);
            uploadFileRequest.setEnableCheckpoint(false);
            uploadFileRequest.setPartSize(partSize); // 设置分片大小
            uploadFileRequest.setTaskNum(taskNum); // 设置并发线程数
//            uploadFileRequest.setTrafficLimit(100000000);

            // 执行断点续传上传
            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
            // 打印上传结果
            log.info("{}文件上传结束,上传路径：{},上传结果：{}",filePath,objectName,uploadResult.getMultipartUploadResult().getETag());
            return true;
        } catch (Throwable e) {
            log.warn("oss上传异常：" , e);
            return false;
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 设置生命周期规则
     */
    public void setLifecycleRule(Integer expirationDays){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            SetBucketLifecycleRequest lifecycleRequest = new SetBucketLifecycleRequest(bucketName);
            LifecycleRule rule = new LifecycleRule();
            rule.setId("loan-contract");
            rule.setPrefix("loan-contract/");
            rule.setStatus(LifecycleRule.RuleStatus.Enabled);
            rule.setExpirationDays(expirationDays);
            lifecycleRequest.AddLifecycleRule(rule);
            ossClient.setBucketLifecycle(lifecycleRequest);
        } catch (Exception e) {
            log.warn("设置生命周期异常 e:",e);
        }finally {
            ossClient.shutdown();
        }
    }

    // 生成带签名和过期时间的URL
    public String generateSignedUrl(String objectName) {
        if(StringUtils.isEmpty(objectName)){
            return null;
        }
        OSS ossClient1 = new OSSClientBuilder().build(downloadEndpoint, accessKeyId, accessKeySecret);
        try{
            if (!ossClient1.doesObjectExist(bucketName,objectName)){
                return null;
            }
            Date expiration = new Date(System.currentTimeMillis() + expirationMin * 60 * 1000L);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
            request.setExpiration(expiration);
            return ossClient1.generatePresignedUrl(request).toString().replace("http://","https://");
        } catch (ClientException e) {
            log.warn("生成oss带签名和过期时间的URL#异常：",e);
            throw new BusinessException("下载异常！");
        }finally {
            ossClient1.shutdown();
        }
    }


    // 生成带签名和过期时间的URL.为项目计划书生成
    public String generateSignedUrlForPlan(String objectName) {
        if (StringUtils.isEmpty(objectName)) {
            return null;
        }
        OSS ossClient1 = new OSSClientBuilder().build(downloadEndpoint, accessKeyId, accessKeySecret);
        try {
            if (!ossClient1.doesObjectExist(bucketName, objectName)) {
                return null;
            }
            //360天
            Date expiration = new Date(System.currentTimeMillis() + expirationMin * 60 * 24 * 1000L);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
            request.setExpiration(expiration);
            return ossClient1.generatePresignedUrl(request).toString().replace("http://","https://");
        } catch (ClientException e) {
            log.warn("生成oss带签名和过期时间的URL#异常：", e);
            throw new BusinessException("下载异常！");
        } finally {
            ossClient1.shutdown();
        }
    }



    public void downloadFile(String objectName, String downloadFilePath) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // Create a GetObjectRequest instance
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            // Download the file to the specified path
            ossClient.getObject(getObjectRequest, new File(downloadFilePath));
        } catch (Exception e) {
            log.error("Error occurred while downloading the file: " + e.getMessage(), e);
        } finally {
            // Ensure the OSS client is properly shut down
            ossClient.shutdown();
        }
    }

}